package com.spring.security.handler;

import com.spring.security.model.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 每当由于未经身份验证的用户尝试访问需要身份验证的资源而引发异常时，都会调用此方法。
 * 如果由于凭据不足够可信而拒绝身份验证请求，则抛出此异常。
 *
 * @author HouKunLin
 */
@Component
@Slf4j
public class NotLoginAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("text/json");
        response.setCharacterEncoding("UTF-8");
        String msg = authException.getMessage();
        if (authException instanceof InsufficientAuthenticationException) {
            msg = "访问此资源需要完全身份验证";
        }
        JsonResult json = JsonResult.status(HttpStatus.UNAUTHORIZED, msg);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().print(json.toJSONString());
    }
}
